TIL — `.nonNulls`

From the source code:

  • flutterbincachedart-sdklibcollectioniterable.dart

/// Operations on iterables with nullable elements.

@Since(“3.0”)

extension NullableIterableExtensions<T extends Object> on Iterable<T?> {

  /// [Returns] The same elements as this iterable,

  /// except that `null` values are omitted.

  Iterable<T> get nonNulls => NonNullsIterable<T>(this);

}

dart:collection

Source — changelog:

Added extension members:

  • nonNulls
  • firstOrNull
  • lastOrNull
  • singleOrNull
  • elementAtOrNull

Obtained by way of:

The pieces I’m most excited about: | Vennom, u/Vennom

    • Sealed classes (so good for relaying state, especially in MVVM/MVI)
    • Records (tuples)
    • Class modifiers (lock your sub-classing down / support for proper interfaces!!)
    • Pattern matching (Destructing)
    • Added extension members on lists: nonNulls, firstOrNull, lastOrNull, singleOrNull, elementAtOrNull and indexed on Iterables.

Obtained by way of:

Dart 3.0: Best New Features & Why You Should Care | Kyle Venn

Obtained by way of:

All of the references above were due to research stemming from my initial spotting of the `nonNulls` helper method available in the intelliSense dropdown from within a DartPad inside the Dart cheatsheet codelab, where I ended up with the following solution — thanks to that intelliSense suggestion:

String joinWithCommas(int a, [int? b, int? c, int? d, int? e]) {
  // Add all params to List.
  // Remove nulls.
  // Join List with comma.
  return <int?>[a, b, c, d, e].nonNulls.join(‘,’);
}


Keith D Commiskey
https://keithdc.com

Leave a Reply